import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt/dist/jwt.service';
import { InjectRepository } from '@nestjs/typeorm';
import { upload } from 'src/utils/qiniu.upload';
import { Repository } from 'typeorm';
import { CreateUserDto } from './dto/create-user.dto';
import { User } from './entities/user.entity';
const axios = require('axios');
const fs = require('fs');
@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
    private readonly jwtService: JwtService,
  ) {}
  //用户登录
  async login(createUserDto: CreateUserDto) {
    const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${process.env.APP_ID}&secret=${process.env.APP_SECRET}&js_code=${createUserDto.code}&grant_type=authorization_code`;
    try {
      const { data } = await axios.get(url);
      const { openid } = data;
      //查找是否注册过
      const result = await this.userRepository.find({
        where: { openId: openid },
      });
      const user = new User();
      user.openId = openid;
      user.nickName = createUserDto.nickName;
      user.avatarUrl = createUserDto.avatarUrl;
      user.gender = createUserDto.gender;
      const payload = {
        id: user.openId,
        nickname: user.nickName,
      };
      const token = this.jwtService.sign(payload);
      //如果注册过 则更新用户数据
      if (result.length) {
        return { token, userInfo: result[0] };
      } else {
        //如果没有注册
        user.nickName = 'Hi Codewheat';
        user.avatarUrl =
          'https://wx.tinyxu.fun/icon%26avatar%26background/iNBox_9.png';
        await this.userRepository.save(user);
        return { token, userInfo: user };
      }
    } catch (err) {
      throw new HttpException(err, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
  async updateAvatar(file: any, openId: string) {
    try {
      let { key } = (await upload(file.path, 'park/' + file.filename)) as {
        hash: string;
        key: string;
      };
      fs.unlinkSync(file.path);
      let avatarUrl = 'https://wx.tinyxu.fun/' + key;
      await this.userRepository.update({ openId }, { avatarUrl });
      return await this.userRepository.find({ where: { openId } });
    } catch (error) {
      throw error;
    }
  }

  async updateNickName(nickName: string, openId: string) {
    await this.userRepository.update({ openId }, { nickName });
    return this.userRepository.find({
      where: { openId },
    });
  }
  async updateGender(gender: number, openId: string) {
    await this.userRepository.update({ openId }, { gender });
    return this.userRepository.find({
      where: { openId },
    });
  }
  async findAll() {
    return await this.userRepository.find({ order: { id: 'DESC' } });
  }
}
